/**
      * Search Family Search - a Ubiquity command for searching for individuals on Family Search
      *
      * BGodard@gmail.com
      *
*/

var uext = Application.extensions.get('ubiquity@labs.mozilla.com');
 
var cookie_mgr = Components.classes["@mozilla.org/cookiemanager;1"]
    .getService(Components.interfaces.nsICookieManager);

CmdUtils.CreateCommand({
    name:"family-search",
    takes: {"name": noun_arb_text},
    modifiers: { "from": noun_arb_text, "born": noun_arb_text},
    icon:'https://devnet.familysearch.org/favicon.ico',
    description: 'Search for family members from your family tree on Family Search',
    help:        
        'Select text on the page to use as the name you want to find, or enter ' +
        'your own text after the command word.' +
        'Note that you must already be logged in at new.familysearch.org to use ' +
        'this command.  Clicking on the displayed name will take you to the person information page.',
    homepage: "",
    author: { 
        name: 'Benjamin Godard', 
        email: 'BGodard@gmail.com' 
    },
      
    /**
     * Command configuration settings.
     */
    _config: {
      // Base URL for the family search API
      api_base: 'http://www.dev.usys.org/familytree/v1/',
      
      // Developer's Key
      key: 'WCQY-7J1Q-GKVV-7DNM-SQ5M-9Q5H-JX3H-CMJK',

      // Domain and name of the Family Search login session cookie.
      cookie_domain: 'dev.usys.org',
      cookie_name:   'USYSSESSIONID'
    },
  
 /**
     * Dig up the login session cookie.
     */
    _getUserCookie: function() {
        var iter = cookie_mgr.enumerator;
        while (iter.hasMoreElements()) {
            var cookie = iter.getNext();
            if( cookie instanceof Components.interfaces.nsICookie && 
                cookie.host.indexOf(this._config.cookie_domain) != -1 && 
                cookie.name == this._config.cookie_name) {
                return decodeURIComponent(cookie.value);
            }
        }
    },
  
/**
     * Given input data and modifiers, attempt to assemble data necessary to
     * search for a name.
     */
    _extractSearchData: function(input_obj, mods) {
        return {
            sessionID:
                this._getUserCookie(),
            name:
                input_obj.text,
            birthPlace:
                mods.from.text || "",
            birthDate:
                mods.born.text || ""
            };
    },  
/**
     * Present a preview of the search
     * 
     */
    preview: function(pblock, input_obj, mods) {
 
      var key = this._config.key;
      var session_cookie = this._getUserCookie();
      //var session_cookie = Utils.getCookie(this._config.cookie_domain, this._config.cookie_name);
      var session_id   = (session_cookie) ? session_cookie.split(' ')[0] : '';
      var input = this._extractSearchData(input_obj, mods);
      //displayMessage(session_cookie);
      var ns = {input: input, key: key};
      var text;
      var searchUrl = this._config.api_base + 'search?';
      
      if (!session_id) {
 
            // If there's no sessionID, there's no login, so this command won't work. 
            text = [ 
                '<p style="color: #d44">No active user found - log in at ', 
                '<img src="https://devnet.familysearch.org/favicon.ico"> ',
              '<b><a style="color: #3774D0" href="http://www.dev.usys.org/identity/v1/login?key=${key}">FamilySearch.org</a></b> ', 
                'to use this command.</p>'
            ].join('');
 
        } else if (!input.name) {
 
            // If there's no Name, then this is an error too.
            text = [ 
                '<p style="color: #d44">A name is required for Searching ',
                '</p>'
            ].join('');    
        
        } else {
          //displayMessage("HI THERE!!!!");
          text = [
                '<style type="text/css">',
                  '.reviewDuplicatesTable {border-bottom:1px solid #42516B; border-collapse:collapse; clear:both; margin:12px 0 0;}',
                  'body, td, th {color:#000000; padding:4px; text-align:left; vertical-align:top;background-color:#D5DEEF; border-bottom:1px solid #A2B0D2; border-right:1px solid #42516B; border-width:1px;font-family:Arial,Helvetica,sans-serif; font-size:small; font-size-adjust:none; font-style:normal; font-variant:normal; font-weight:normal; line-height:normal;}',
                  'th {padding:4px; text-align:left; kvertical-align:top;background:#FFFFFF url(../images/bck_compare_repeat-x.gif) repeat-x scroll center bottom; border-bottom:1px solid #42516B; border-right:1px solid #C6C3B9; border-width:1px; color:#635942; font-weight:bold;}',
                  'a {color:#182A4B;}',
                  'a:hover { color:#000000;}',
                '</style>',
                '<table class="duplicatesTable" cellspacing="0" cellpadding="0" border="0" summary="List of Possible Duplicate Records">',
                '<tr><th>Name</th><th>Birth Date</th><th>Place</th></tr>'
            ].join('');
          // Do Search
          var params = {sessionId: session_id, name: input.name,  birthDate: input.birthDate, birthPlace: input.birthPlace, maxResults: "5"};
          var index = 0;
          //CmdUtils.setSelection(searchUrl + jQuery.param(params));
          displayMessage(searchUrl + jQuery.param(params));
          CmdUtils.previewAjax(pblock,{
            type: "GET",
            url: searchUrl,
            data: params,
            dataType: "xml",
            success: function(xml){
              //displayMessage(jQuery(xml).text());
              jQuery(xml).find("search > person").each(function(){
              //displayMessage("HEY2");
              var id = "p." + jQuery(this).attr("ref");
              text+=('<tr>')
              text+=('<td>');
              text+=('<a href="http://www.dev.usys.org/en/action/hourglassiconicview?bookid=' + id + '&focus=' + id +'&svfs=1">');
              text+=(jQuery(this).find("fullText").text());
              text+=('</a>');
              text+=('</td>');
              text+=('<td>');
              text+=(jQuery(this).find("event[type='Birth'] > date").text());
              text+=('</td>');
              text+=('<td>');
              text+=(jQuery(this).find("event[type='Birth'] > place").text());
              text+=('</td>');

              text+=('</tr>');
              //displayMessage(index++);
              });
              //displayMessage(text);
              pblock.innerHTML = text + "</table>";
            },
            error: function(xml){
              displayMessage("UhOH: " + searchUrl + jQuery.params(params));
            }
          });
          //text+=('</table>');
          //text = [ 
            //'<p>Search For: ${input.firstName} ${input.middleName}. ${input.lastName}</p>'
          //].join("\n");
          
        }
      //displayMessage("HI THERE2!!!!");
      //displayMessage(text);
      pblock.innerHTML = CmdUtils.renderTemplate(text, ns);
    }   
})



